package nbcp.db.sys

import nbcp.base.comm.ApiResult
import nbcp.db.IdName
import nbcp.base.*
import nbcp.base.comm.JsonResult
import nbcp.base.extend.AsString
import nbcp.base.extend.Corp
import nbcp.base.extend.HasValue
import nbcp.base.utils.CodeUtil
import nbcp.base.utils.Md5Util
import nbcp.db.LoginUserModel
import nbcp.db.mongo.entity.SysUser
import nbcp.db.mongo.mor
import nbcp.db.mongo.*
import nbcp.db.mongo.entity.SysLoginUser
import nbcp.db.mongo.table.SystemGroup
import nbcp.web.LoginUser
import java.time.Duration
import java.time.LocalDateTime
import java.util.*
import javax.servlet.http.HttpServletRequest

/**
 * Created by udi on 17-5-23.
 */

/**
 * 登录验证，返回错误消息
 */
fun SystemGroup.SysUserEntity.doLogin(loginName: String, password: String, request: HttpServletRequest): ApiResult<SysUser> {
    var user = mor.system.sysUser.query()
            .where { (it.loginName match loginName) match_or (it.mobile match loginName) }
            .toEntity()

    if (user == null) {
        return ApiResult("找不到用户: ${loginName}", "loginName")
    }


    var loginName = user.loginName
    var login_user = mor.system.sysLoginUser.query()
            .where { it.loginName match loginName }
            .toEntity();

    if (login_user == null) {
        return ApiResult("用户被禁用登录: ${loginName}", "loginName")
    }

    if (login_user.errorLoginTimes > 5 && (LocalDateTime.now() - login_user.lastLoginAt).totalMinutes < 5) {
        return ApiResult("帐户频繁登录失败，已被锁定5分钟！")
    }

    if (login_user.password != Md5Util.getBase64Md5(password)) {
        mor.system.sysLoginUser.update()
                .set { it.lastLoginAt to LocalDateTime.now() }
                .set { it.errorLoginTimes to login_user.errorLoginTimes + 1 }
                .where { it.loginName match loginName }
                .exec();

        return ApiResult("密码错误，登录失败", "password")
    }


    var token = request.session.id;
    user.token = token;

    request.LoginUser = LoginUserModel(user.id, user.loginName, user.name,user.token);
    request.Corp = user.corp

    mor.system.sysLoginUser.update()
            .set { it.lastLoginAt to LocalDateTime.now() }
            .set { it.errorLoginTimes to 0 }
            .where { it.loginName match loginName }
            .exec();

    mor.system.sysUser.update()
            .where { it.loginName match loginName }
            .set { it.token to token }
//            .set { it.regionId to regionId }
            .set { it.lastLoginAt to LocalDateTime.now() }
            .exec();

    return ApiResult.of(user)
}

fun SystemGroup.SysUserEntity.doRegiste(loginName: String, mobile: String, email: String, password: String): JsonResult {
    var sysUser = SysUser();
    sysUser.loginName = loginName;
    sysUser.email = email;
    sysUser.mobile = mobile;

    mor.system.sysUser.insert(sysUser);

    if (mor.affectRowCount == 0) {
        return JsonResult("插入数据失败")
    }

    var loginUser = SysLoginUser();
    loginUser.loginName = loginName;
    loginUser.password = Md5Util.getBase64Md5(password);
    mor.system.sysLoginUser.insert(loginUser);

    if (mor.affectRowCount == 0) {
        return JsonResult("插入数据失败")
    }

    return JsonResult();
}
////添加角色
//fun ProxyRepository<SysUser,SystemGroup.SysUserEntity>.addRole(objectId: String, role: IdName): Int {
//    /**
//     * db.sysUser.update({"_id" : ObjectId("58dcb7c7e8f66e12005a4c3e")},{"email":"oka"});
//     * update sysUser set email = 'oka' where id = '58dcb7c7e8f66e12005a4c3e'
//     *
//     * db.sysUser.update(
//     *  {"_id" : ObjectId("58dcb7c7e8f66e12005a4c3e")},
//     *  {"$push":{"role":{"id":"12","name":"lan"}}})
//     */
//    var result = mor.mongoTemplate.updateFirst(
//            query.query(Criteria.where("id").`is`(ObjectId(objectId))),
//            org.springframework.data.mongodb.core.query.Update().push("role", role),
//            SysUser::class.java);
//
//    return result.modifiedCount.toInt();
//}
//
////修改角色
//fun ProxyRepository<SysUser>.updateRole(objectId: String, index: Int, role: IdName): Int {
//    /**
//     * db.sysUser.update({"_id" : ObjectId("58dcb7c7e8f66e12005a4c3e")},{"email":"oka"});
//     * update sysUser set email = 'oka' where id = '58dcb7c7e8f66e12005a4c3e'
//     *
//     * db.sysUser.update(
//     *  {"_id" : ObjectId("58dcb7c7e8f66e12005a4c3e")},
//     *  {"$push":{"role":{"id":"12","name":"lan"}}})
//     */
//    //是修改 query query = new query(Criteria.where("cid").is(cid).and("voiceLibrarys.lid").is(lid)); Update update = Update.update("voiceLibrarys.$.title", title).set("voiceLibrarys.$.content", content); mongoTemplate.updateFirst(query, update, MgVoice.class);
////是修改
////
//// query query = new query(Criteria.where("cid").is(cid).and("voiceLibrarys.lid").is(lid));
//// Update update = Update.update("voiceLibrarys.$.title", title).set("voiceLibrarys.$.content", content);
//// mongoTemplate.updateFirst(query, update, MgVoice.class);
///*
//db.sysUser.update(
//{ "_id":ObjectId("58dcc7e0b69b336a71c724c6"), "role._id":"12" } ,
//{ "$set": {"role.$.name":"--eeee--"}  });
// */
//    //var bson = BsonDocument();
//
//    var result = mor.mongoTemplate.updateFirst(
//            query.query(Criteria.where("id").`is`(ObjectId(objectId))),
//            org.springframework.data.mongodb.core.query.Update.update("role.${index}._id", role.id).set("role.${index}.name", role.name),
//            SysUser::class.java);
//
//    return result.modifiedCount.toInt();
//}
